<template>
  <a-layout-footer style="text-align: center">
    wiki电子书网站@2024-10
    <span v-show="user.name != undefined && user.name != ''"
      >欢迎：{{ user.name }}</span
    >
  </a-layout-footer>
</template>

<script lang="ts">
import { defineComponent, computed, onMounted } from "vue";
import store from "@/store";
import { Tool } from "@/utils/tool";
import { notification } from "ant-design-vue";
export default defineComponent({
  name: "the-footer",
  setup() {
    //从store中获取user对象数据
    const user = computed(() => store.state.user);
    //声明websocket和token
    let websocket: any;
    let token: any;
    //链接成功的回调
    const onOpen = () => {
      console.log("WebSocket连接成功，状态码：", websocket.readyState);
    };
    //收到消息的回调
    const onMessage = (event: any) => {
      console.log("WebSocket收到消息：", event.data);
      notification["info"]({
        message: "收到消息",
        description: event.data,
      });
    };
    //出现错误的回调
    const onError = () => {
      console.log("WebSocket连接错误，状态码：", websocket.readyState);
    };
    //关闭链接的回调
    const onClose = () => {
      console.log("WebSocket连接关闭，状态码：", websocket.readyState);
    };
    //初始化WebSocket
    const initWebSocket = () => {
      // 连接成功
      websocket.onopen = onOpen;
      // 收到消息的回调
      websocket.onmessage = onMessage;
      // 连接错误
      websocket.onerror = onError;
      // 连接关闭的回调
      websocket.onclose = onClose;
    };
    //在mouted生命周期中加载websocket
    onMounted(() => {
      // WebSocket
      if ("WebSocket" in window) {
        token = Tool.uuid(10);
        // 连接地址：ws://127.0.0.1:8880/ws/xxx
        websocket = new WebSocket(
          process.env.VUE_APP_WS_SERVER + "/ws/" + token
        );
        //初始化
        initWebSocket();
        // 关闭
        // websocket.close();
      } else {
        alert("当前浏览器 不支持");
      }
    });
    //返回user
    return {
      user,
    };
  },
});
</script>
